package com.freeLearning.boot.course.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.freeLearning.boot.common.annotation.Log;
import com.freeLearning.boot.common.enums.AuditStatusEnum;
import com.freeLearning.boot.common.enums.LogModuleEnum;
import com.freeLearning.boot.common.result.Result;
import com.freeLearning.boot.core.security.util.SecurityUtils;
import com.freeLearning.boot.course.enums.StatusEnum;
import com.freeLearning.boot.course.model.VO.CourseAuditPageVO;
import com.freeLearning.boot.course.model.VO.CourseInfoVO;
import com.freeLearning.boot.course.model.entity.CourseAudit;
import com.freeLearning.boot.course.model.entity.CourseAuditHistory;
import com.freeLearning.boot.course.model.entity.CourseChapters;
import com.freeLearning.boot.course.model.entity.CourseInfo;
import com.freeLearning.boot.course.model.query.CourseInfoPageQuery;
import com.freeLearning.boot.course.service.CourseAuditHistoryService;
import com.freeLearning.boot.course.service.CourseAuditService;
import com.freeLearning.boot.course.service.CourseChaptersService;
import com.freeLearning.boot.course.service.CourseInfoService;
import com.freeLearning.boot.shared.mail.service.MailService;
import com.freeLearning.boot.system.enums.MessageEnum;
import com.freeLearning.boot.system.model.entity.ConsultantAudit;
import com.freeLearning.boot.system.model.entity.Message;
import com.freeLearning.boot.system.model.entity.User;
import com.freeLearning.boot.system.service.MessageService;
import com.freeLearning.boot.system.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.C;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Tag(name = "20.课程审批接口")
@RequestMapping("/api/v1/course/audit")
@RestController
@RequiredArgsConstructor
public class CourseAuditController {

    private final CourseAuditService courseAuditService;
    private final CourseAuditHistoryService courseAuditHistoryService;
    private final CourseInfoService courseInfoService;
    private final CourseChaptersService courseChaptersService;
    private final UserService userService;
    private final MailService mailService;
    private final MessageService messageService;
    @PostMapping("/page")
    @Operation(summary = "分页查询课程审批")
    @Log(value = "分页查询课程审批", module = LogModuleEnum.COURSEINFO_AUDIT)
    public Result<IPage<CourseAuditPageVO>> page(@RequestBody CourseInfoPageQuery courseInfoPageQuery) {
        IPage<CourseAuditPageVO> page = courseAuditService.pageQuery(courseInfoPageQuery);
        return Result.success(page);
    }

    @PostMapping("/audit")
    @Operation(summary = "课程审批")
    @Log(value = "课程审批", module = LogModuleEnum.COURSEINFO_AUDIT)
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> audit(@RequestBody CourseAudit courseAudit) {
        boolean aStatus = courseAuditService.update(courseAudit, new UpdateWrapper<CourseAudit>().eq("course_id", courseAudit.getCourseId()).set("status", courseAudit.getStatus()).set("audit_time", LocalDateTime.now()));
        boolean hStatus = courseAuditHistoryService.save(BeanUtil.copyProperties(courseAudit, CourseAuditHistory.class));
        boolean update = courseInfoService.update(new UpdateWrapper<CourseInfo>().eq("id", courseAudit.getCourseId()).set("status", courseAudit.getStatus()));
        boolean isPass = courseAudit.getStatus().equals(StatusEnum.WAIT_PUBLISH.getValue());

        Long userId = SecurityUtils.getUserId();
        CourseInfo courseInfo = courseInfoService.getById(courseAudit.getCourseId());
        Long acceptId = courseInfo.getConsultantId();
        User user = userService.getById(acceptId);
        if (user.getEmail() != null){
            mailService.sendHTMLMail(
                    user.getEmail(),
                    (isPass ? "课程审核通过" : "课程审核未通过"),
                    getFormattedMailContent(courseAudit,isPass),
                    false
            );
        }
        StringBuilder messageContent = new StringBuilder();
        if (isPass) {
            messageContent.append("您的课程《")
                    .append(courseInfoService.getById(courseAudit.getCourseId()).getTitle())
                    .append("》审核通过，可以发布啦。");
        }else{
            messageContent.append("您的课程《")
                    .append(courseInfoService.getById(courseAudit.getCourseId()).getTitle())
                    .append("》审核不通过，审批意见：")
                    .append(courseAudit.getOpinion())
                    .append(",请修改后重新提交。");
        }
        Message message = Message.builder()
                .title(isPass ? "课程审核通过" : "课程审核不通过")
                .content(messageContent.toString())
                .type(isPass ? MessageEnum.COURSE_AUDIT_PASS.getValue() : MessageEnum.COURSE_AUDIT_NOT_PASS.getValue())
                .publisherId(userId)
                .publishTime(LocalDateTime.now())
                .createBy(userId)
                .acceptId(acceptId)
                .other(JSONUtil.toJsonStr(courseAudit))
                .build();
        messageService.sendMessage(message);
        return Result.success(aStatus && hStatus && update);
    }

    @GetMapping("/info/{id}")
    @Operation(summary = "查询课程详情")
    @Log(value = "查询课程详情", module = LogModuleEnum.COURSEINFO_AUDIT)
    public Result<CourseInfoVO> getById(@PathVariable Long id) {
        CourseInfoVO courseInfoVO = new CourseInfoVO();
        CourseInfo courseInfo = courseInfoService.getById(id);
        BeanUtil.copyProperties(courseInfo, courseInfoVO);
        List<CourseChapters> chapters = courseChaptersService.list(new UpdateWrapper<CourseChapters>().eq("course_id", id));
        courseInfoVO.setChapters(chapters);
        courseInfoVO.setChaptersNum(chapters.size());
        return Result.success(courseInfoVO);
    }

    @GetMapping("/history/{id}")
    @Operation(summary = "查询课程审批历史")
    @Log(value = "查询课程审批历史", module = LogModuleEnum.COURSEINFO_AUDIT)
    public Result<List<CourseAuditHistory>> getHistoryById(@PathVariable Long id) {
        return Result.success(courseAuditHistoryService.list(new QueryWrapper<CourseAuditHistory>().eq("course_id", id)));
    }
    private String getFormattedMailContent(CourseAudit courseAudit,Boolean isPass) {
        StringBuilder content = new StringBuilder();
        content.append("<html><body style='font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>");
        content.append("<div style='background-color: #ffffff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'>");

        // 添加平台Logo和标题
        content.append("<img src='http://www.free-learning.icu/images/logo.png' alt='公益性教育咨询平台' style='width: 150px; height: auto; display: block; margin: 0 auto;'><br>");
        content.append("<h1 style='color: #333333; text-align: center;'>审核结果通知</h1>");

        // 用户问候
        content.append("<p style='color: #666666;'>尊敬的咨询师：</p>");
        content.append("<p style='color: #666666;'>您的课程审核结果如下：</p>");

        // 审核状态、意见和审核人
        content.append("<p style='color: #666666;'><strong style='color: #333333;'>审核状态：</strong>")
                .append(isPass ? "审核通过" : "审核未通过")
                .append("</p>");
        content
                .append("<p style='color: #666666;'><strong style='color: #333333;'>审核意见：</strong>")
                .append(courseAudit.getOpinion())
                .append("</p>");
        content
                .append("<p style='color: #666666;'><strong style='color: #333333;'>审核人：</strong>")
                .append(courseAudit.getAuditorName())
                .append("</p>");

        // 动态提示信息
        if (isPass) {
            content.append("<p style='color: #28a745;'>恭喜您，审核通过！您可以在课程维护界面对您的课程进行维护与发布。</p>");
        } else {
            content.append("<p style='color: #dc3545;'>审核未通过，请根据审核意见进行修改。</p>");
        }

        // 平台信息和链接
        content.append("<p style='color: #666666;'>感谢您使用我们的服务！如果您有任何疑问，请访问我们的官网：<a href='http://www.free-learning.icu/' style='color: #007bff;'>公益性教育咨询平台</a></p>");
        content.append("<p style='color: #666666;'>祝您使用愉快！</p>");

        content.append("</div>");
        content.append("</body></html>");
        return content.toString();
    }
}
